<?php
/**
 * 投票  整合秒杀功能
 * @example 目前支持cookie
 * @author wolf
 * @version 1.0
 */
class VoteController extends NodeController
{
    protected $_template = "hdd_vote_list.tpl"; //配置投票模板
    protected $_vote_field = 113; //投票字段
    protected $_limit_type = 'cookie'; //cookie 目前支持cookie
    protected $_limit_num = 50; //投票数目
    protected $_goodsnum_fild = 115; //产品数量
    protected $_code = "abcdefghijklmnopqrst123456789";
    protected $_luck = array(
            '854' => 1,
            '435' => 2,
            '236' => 3);
    /**
     * 
     * 候选人名单
     * @var unknown_type
     */
    protected $_candidate = array(
            '27744',
            '27182');
    
    
    /**
     * 配置要参与的企业
     * 
     */
    public function config()
    {
        $rs = VoteModel::instance()->getAllConfig();
        $this->view()->assign('attr', $rs);
        $this->view()->assign('cachetype', 1);
        $this->view()->clearCache("file:news/active.tpl");
        $this->view()->clearCompiledTemplate("file:news/active.tpl");
        $this->view()->display("file:news/active.tpl");
    
    }
    
    public function saveConfig()
    {
        
        if ($_POST) {
            
            $param = array(
                    'people' => trim($_POST['people']),
                    'active_name' => trim($_POST['active_name']),
                    'template' => trim($_POST['template']),
                    'limit_num' => trim($_POST['limit_num']));
            foreach ($param as $k => $v) {
                VoteModel::instance()->setConfig(array(
                        'value' => $v), array(
                        'name' => $k));
            }
            $this->redirect("更新成功!", "/vote/config");
        }
    }
    
    /**
     * 投票首页  可以自定义绑定模板 
     * 比起其他自定义模板   还有其他参数
     * 投票队列
     * 投票ip地址
     * 
     */
    public function i()
    {
        $temp = "mysql:" . $this->_template;
        
        //如果启用了每台电脑抽奖 配置在缓存之前
        $user = $this->getVoteUserByCookie();
        $this->view()->clearCache($temp);
        
        if (isset($_GET['cache']) && $_GET['cache'] == "no") {
            $this->view()->clearCompiledTemplate($temp);
        }
        if ($this->view()->isCached($temp)) {
            $this->view()->display($temp);
            exit();
        }
        
        $this->view()->assign('user', $user);
        $this->view()->display($temp);
    }
    
    /**
     * 获取候选人信息导入到候选人名单w_vote_list
     * 
     */
    public function candidate()
    {
        return VoteModel::instance()->getVoteList();
    }
    
    /**
     * 凭此号码 来获取奖品
     * 
     */
    public function getVoteUserByCookie()
    {
        if (! isset($_COOKIE['ss'])) {
            $code = $this->checkUsername($this->createCode(8)); //检查是否重复
            setcookie("ss", $code, time() + 3600 * 24, "/"); /*1天*/
            /*新增参赛人员*/
            $people = VoteModel::instance()->getConfig(array(
                    'name' => "people"));
            /*更新参赛人数*/
            $ip = $this->getIP();
            VoteModel::instance()->updatePeople();
            $bianhao = $people['value'] + 1;
            $pargams = array(
                    'username' => $code,
                    'ip' => $ip['ip'],
                    'num' => 0,
                    'address' => $ip['country'] . $ip['area'],
                    'add_time' => time());
            
            VoteModel::instance()->addUser($pargams);
            return $pargams;
        } else {
            $rs = VoteModel::instance()->getUserVoteNum(array(
                    "username" => $_COOKIE['ss']));
            return $rs;
        }
    }
    
    /**
     * 通过cookie来投票 正式版本
     * 
     */
    protected function checkUserByCookie()
    {
        
        if (! isset($_COOKIE['ss'])) {
            $this->sendNotice("你无法投票，请启用浏览器cookie!", null, false);
            exit();
        }
        
        $user = VoteModel::instance()->getUserVoteNum(array(
                'username' => $_COOKIE['ss']));
        
        //这里你可以设置更多的规则
        

        if ($user['num'] >= $this->_limit_num) {
            $this->sendNotice("你的投票数已用完，谢谢参与", null, false);
            exit();
        }
        //增加投票数
        $num = $user['num'] + 1;
        VoteModel::instance()->saveVoteUser(array(
                'num' => $num), array(
                'username' => $user['username']));
        return $user;
    }
    
    /**
     * 增加福袋
     * Enter description here ...
     */
    public function fd()
    {
        
        $zf = array(
                "恭喜发财,再来一次",
                "好运相伴,再来一次",
                "新年行大运,再来一次哦",
                "马上有钱,马到成功,再来一次",
                "网络管理部祝大家新年快乐",
                "顶上-生活之上",
                "全国免费招商热线<br>0573-83253333",
                "一马当先,再来一次",
                "甜甜蜜蜜,幸福一生");
        $rand = rand(0, 8);
        $this->sendNotice($zf[$rand], null, success);
    }
    
    /**
     * 
     * ip
     */
    protected function checkUserByIp()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $user = VoteModel::instance()->getVoteUser(array(
                'username' => $ip));
        if (! empty($user)) {
            $udate = date("md", $user['add_time']);
            $now = date("md", time());
            
            if ($udate == $now) {
                $this->sendNotice("今天投票次数已经用完", null, false);
                exit();
            }
        } else {
            //添加投票历史记录
            $params = array(
                    'username' => $ip,
                    'add_time' => time());
            VoteModel::instance()->addVoteUser($params);
        }
    }
    /**
     * 一个ip只能投一次  配置好字段 扩展字段
     * 
     */
    public function ipt()
    {
        
        $gid = $_POST['id'];
        //进行过滤  
        

        //增加1 即可
        $user = $this->checkUserByCookie();
        
        VoteModel::instance()->saveExtendValue($this->_vote_field, $gid);
        //添加历史记录
        $time = time();
        $params = array(
                'uid' => $user['id'],
                'voteid' => $gid,
                'add_time' => $time);
        
        VoteModel::instance()->addVoteHistory($params);
        $this->sendNotice("投票成功", null, true);
        exit();
    
    }
    
    /**
     * 秒杀凭证页面
     * Enter description here ...
     */
    public function kl()
    {
        if (! isset($_SESSION['uid'])) {
            $this->sendNotice("请先登录哦！", 0, false);
            exit();
        }
        
        $user = unserialize($_SESSION['uid']);
        $rs = VoteModel::instance()->getKillHistoryByWhere($user['uid']);
        $this->view()->assign('rs', $rs);
        $this->view()->clearCache("mysql:kill_list.tpl");
        $this->view()->clearCompiledTemplate("mysql:kill_list.tpl");
        
        $this->view()->display("mysql:kill_list.tpl");
    }
    /**
     * 秒杀功能
     * 第一个人抢的时候 对商品信息进行存储
     *
     */
    public function kill()
    {
        
        $limitNum = 5;
        //检查是否登录
        if (! isset($_SESSION['uid'])) {
            $this->sendNotice("请先登录哦！", 0, false);
            exit();
        }
        
        $begin = "2014/03/04 16:50:00";
        $starttime = strtotime($begin);
        $time = time();
        $date = date("Y/m/d H:i:s", $time);
        if ($starttime > $time) {
            $this->sendNotice("还未开始哦！当前时间$date", 0, false);
            exit();
        }
        
        $user = unserialize($_SESSION['uid']);
        
        /* procedural API */
        $gid = trim($_POST['gid']);
        $num = trim($_POST['num']);
        /* OO API */
        $redis = new Redis();
        if (! $redis->connect('127.0.0.1', 6379)) {
            throw new Exception("无法链接redis!");
        }
        
        $max = $redis->get("max");
        if (! $max) {
            $max = 1;
        } else {
            $max ++;
        }
        if ($max > 300) {
            $this->sendNotice("活动已经结束", 0, false);
            exit();
        }
        $redis->set("max", $max);
        $params = array(
                'uid' => $user['uid'],
                'username' => $user['username'],
                'goodsid' => $gid,
                'num' => $num,
                'add_time' => $time,
                'sort' => $max);
        
        $redis->rPush('dl', serialize($params));
        $ginfo = $redis->get($gid);
        $ginfo = unserialize($ginfo);
        //配置商品信息
        if ($ginfo == null) {
            $ginfo = array(
                    'id' => $gid,
                    'num' => $limitNum - $num,
                    'start' => "2014/02/28 17:00:00");
        } else {
            $ginfo['num'] = $ginfo['num'] - $num;
        }
        $redis->set($gid, serialize($ginfo));
        
        if ($ginfo['num'] < 0) {
            $error = "你来晚了,抢购一空,你排在第" . $max . "位,剩余奖品数目" . $ginfo['num'];
            $this->sendNotice($error, 0, false);
            exit();
        
        }
        $message = "抢购成功,你排在第" . $max . "位,剩余奖品数目" . $ginfo['num'];
        
        $this->sendNotice($message, 0, true);
    
     //增加一笔订单
    /*

        VoteModel::instance()->addKillOrder($params);
        //更新剩余数量
        VoteModel::instance()->saveKillNum($gid, $this->_goodsnum_fild, $num);
        $this->sendNotice("恭喜你，秒杀成功！$num 件", $rs['int'] - $num, true);*/
    
    }
    
    /*处理秒杀队列*/
    public function execList()
    {
        echo "<h1>秒杀活动抢购队列</h1><br>";
        $redis = new Redis();
        if (! $redis->connect('127.0.0.1', 6379)) {
            throw new Exception("无法链接redis!");
        }
        $length = $redis->lSize('dl');
        $i = 0;
        while ($i < $length) {
            $u = unserialize($redis->lGet('dl', $i));
            $i ++;
            
            echo '#' . $i . " [" . date("m/d H:i:s", $u['add_time']) . "] " . $u['username'] . "<br>";
        }
    
    }
    
    public function redis()
    {
        if ($_GET['cache'] == 'all') {
            $redis = new Redis();
            if (! $redis->connect('127.0.0.1', 6379)) {
                throw new Exception("无法链接redis!");
            }
            
            $redis->flushAll();
            echo "redis已经重置";
        }
    }
    
    /**
     * 获取统计
     * Enter description here ...
     */
    public function getConfig()
    {
        $tj = VoteModel::instance()->getAllConfig();
        $ntj = array();
        foreach ($tj as $v) {
            $ntj[$v['name']] = $v['value'];
        }
        return $ntj;
    }
    
    /**
     * 获得ip地址
     *
     * @return array $arrIp (ip country area)
     */
    protected function getIp()
    {
        $ip = new IpLocation();
        $clientIp = $ip->getIP();
        
        $rs = $ip->getlocation($clientIp);
        unset($rs['beginip']);
        unset($rs['endip']);
        foreach ($rs as $k => $v) {
            $v = iconv('GB2312', 'UTF-8', $v);
            $arrIp[$k] = $v;
        }
        return $arrIp;
    }
    
    /**
     * 提交抢楼
     * data 1
     */
    public function comment()
    {
        
        if (isset($_POST['uid']) && ! empty($_POST['uid'])) {
            $user = $this->setUsername();
            
            if ($user['num'] >= 1) {
                
                echo json_encode(array(
                        'status' => false,
                        'error' => "你还未完成投票数哦,还差$user[num]票",
                        "data" => 0));
                exit();
            }
            /*防止多开浏览器进行疯抢,对时间进行判断 timestamp*/
            if (time() - strtotime($user['time']) < 13) {
                echo json_encode(array(
                        'status' => false,
                        'error' => "亲,可能开了2个浏览器,请不要作弊哟!",
                        "data" => 0));
                exit();
            }
            
            //验证码是否正确
            // $code = SecureCode::getInstance();
            //$code = $code->getCode();
            //   var_dump($code->verify($_POST['code']));
            //    $this->checkCode();
            /*正确之后 进行排队*/
            $pd = VoteModel::instance()->getConfig(array(
                    "name" => "paidui"));
            
            /*当前排队数*/
            $newPd = $pd['value'] + 1;
            
            if ($newPd > 888) {
                echo json_encode(array(
                        'status' => false,
                        'error' => "活动达到888楼，请继续关注中国LED品牌网",
                        "data" => 0));
                exit();
            }
            
            /*更新楼层*/
            VoteModel::instance()->updateLc();
            /*获奖算法*/
            
            if ($newPd == 8 || substr($newPd, - 1) == 8) {
                /*写入获奖队伍*/
                VoteModel::instance()->addLuck(array(
                        "username" => $_COOKIE['code'],
                        "bianhao" => $_POST['uid'],
                        "postion" => $newPd,
                        'date' => time(),
                        "remark" => "精品袜子"));
                /*中奖数+1*/
                $zhongjiang = true;
                VoteModel::instance()->updateLuckNum();
            }
            
            /*特等奖存放处*/
            if ($this->_luck[$newPd] > 0) {
                $remark = $this->_luck[$newPd] . "等奖";
                VoteModel::instance()->addLuck(array(
                        "username" => $_COOKIE['code'],
                        "bianhao" => $_POST['uid'],
                        "postion" => $newPd,
                        'date' => time(),
                        "remark" => $remark));
                $zhongjiang = true;
                $tdj = true;
            }
            /*统计个人抢楼次数*/
            
            VoteModel::instance()->updateUserQlnum($_POST['uid'], $zhongjiang);
            /*添加抢楼详情页*/
            VoteModel::instance()->addQl(array(
                    'uid' => $_POST['uid'],
                    'lc' => $newPd,
                    'date' => time(),
                    'username' => $_COOKIE['code']));
            
            if ($tdj) {
                echo json_encode(array(
                        'status' => true,
                        'error' => "请再接再励,当前楼层为$newPd",
                        'lc' => $newPd . "楼" . $remark,
                        "data" => $this->_luck[$newPd]));
                exit();
            }
            
            if ($zhongjiang) {
                echo json_encode(array(
                        'status' => true,
                        'error' => "恭喜获得精美袜子一双, 楼层为$newPd",
                        'lc' => $newPd,
                        "data" => 4));
                exit();
            } else {
                echo json_encode(array(
                        'status' => true,
                        'error' => "请再接再励,当前楼层为$newPd",
                        'lc' => $newPd,
                        "data" => 0));
                exit();
            }
            if (empty($_POST['uid'])) {
                //系统出错
            }
        
     //添加详情页
        //增加楼层数
        //增加个人抢楼几次
        //是否获奖
        

        }
    }
    
    protected function checkUsername($username)
    {
        $rs = VoteModel::instance()->getVoteUser(array(
                "username" => $username));
        if (! empty($rs)) {
            $username = $this->createCode(8);
            $this->checkUsername($username);
        }
        return $username;
    }
    
    public function createvaild()
    {
        $captcha = new Captcha(80, 30, 4);
        $captcha->showImg();
    }
    /**
     * 分页
     *
     * @return void
     */
    protected function page($total, $num = 5)
    {
        $pageid = isset($_GET['p']) ? $_GET['p'] : 1;
        
        $rs = $pageid * $num - $total;
        
        $start = ($pageid - 1) * $num;
        $pagenum = ceil($total / $num);
        
        $page = array(
                'start' => $start,
                'num' => $num,
                'current' => $pageid,
                'page' => $pagenum);
        return $page;
    }
    
    /**
     * 领奖页面
     */
    public function lj()
    {
        $jp = array(
                "socks" => "精品袜子",
                "first" => "1等奖",
                "second" => "2等奖",
                "third" => "3等奖");
        $user = $this->setUsername();
        $rs = VoteModel::instance()->getLuckByWhere(array(
                'username' => $_COOKIE['code']));
        
        //进行计算
        $tj = array(
                "socks" => 0,
                "first" => 0,
                "second" => 0,
                "third" => 0);
        foreach ($rs as $v) {
            foreach ($jp as $k => $jv) {
                if ($v['remark'] == $jv) {
                    $tj[$k] += 1;
                }
            }
        }
        
        $i = $this->getConfig();
        $tj['people'] = $i['people'];
        $this->view()->assign("user", $user);
        
        $this->view()->assign("tj", $tj);
        $this->view()->display("mysql:prizes.tpl");
    }
    
    /**
     * 收货地址
     */
    public function address()
    {
        if ($_POST) {
            $user = $this->setUsername();
            $params = array(
                    'bianhao' => $user['uid'],
                    'shr' => trim($_POST['shr']),
                    'mobile' => $_POST['mobile'],
                    'address' => trim($_POST['address']));
            $rs = VoteModel::instance()->getAddress(array(
                    'bianhao' => $user['uid']));
            if (empty($rs)) {
                VoteModel::instance()->addAddress($params);
            } else {
                VoteModel::instance()->updateAddress($params, array(
                        'bianhao' => $user['uid']));
            }
            $this->redirect("提交成功", "/vote/lj");
        }
    }
    
    /**
     * 对其进行验证  用户flash接口
     */
    public function fapi()
    {
        //配置概率    
        $prices = array(
                "1" => "费列罗",
                "2" => "心跳一刻",
                "3" => "德芙巧克力",
                "4" => "谢谢惠顾",
                "5" => "加油好男儿");
        $int = rand(1, 100);
        
        switch ($int) {
            case $int < 50 :
                $getPrices = 5;
                break;
            case $int >= 50 && $int < 70 :
                $getPrices = 2;
                break;
            case $int >= 70 && $int < 95 :
                $getPrices = 4;
                break;
            case $int >= 95 && $int < 98 :
                $getPrices = 3;
            case $int >= 98 :
                $int = 1;
                break;
        
        }
        //    $getPrices = $prices[$int];
        

        $user = $_COOKIE['user']; //检查用户是否存在
        if (empty($user)) {
            $error = "<a href='http://www.d-shang.com/anonymous/login' target='__blank'>请先登录</a>";
            echo "status=false&error=$error&data=null";
            exit();
        }
        
        //必须先注册才能进行登录       
        $db = VoteModel::instance()->getVoteUser(array(
                'username' => $user));
        
        if (! empty($db)) {
            if ($db['num'] < 1) {
                echo "status=false&error=抽奖次数$db[num]";
                exit();
            }
            
            echo "status=true&error=$db[num]&data=$getPrices";
            VoteModel::instance()->addLuck(array(
                    'username' => $db['username'],
                    'remark' => $prices[$getPrices],
                    'add_time' => time()));
            //抽奖次数减去1
            $num = $db['num'] - 1;
            VoteModel::instance()->saveVoteUser(array(
                    'num' => $num), array(
                    'username' => $user));
        
     //echo $db['username'];
        } else {
            //配置抽奖机会和奖品  当前+2次=3次机会
            VoteModel::instance()->addVoteUser(array(
                    'username' => $user,
                    'add_time' => time(),
                    'num' => 6));
            echo "status=true&error=新用户&data=" . $getPrices;
        }
        exit();
    }
    
    /**
     * 生成识别码
     */
    protected function createCode($num)
    {
        $str = "23456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKMNPQRSTUVWXYZ";
        
        for ($i = 0; $i < $num; $i ++) {
            $code .= $str{rand(0, strlen($str) - 1)};
        }
        
        return $code;
    }

}